/**
 * @a https://leetcode.cn/problems/as-far-from-land-as-possible/
 */

#include "../../common.h"

class Solution {
    vector<vector<bool>> vis;
public:
    int maxDistance(vector<vector<int>>& grid) {
        const static int dx[4] = {0,0,1,-1};
        const static int dy[4] = {1,-1,0,0};

        int n = grid.size();
        vis.resize(n,vector<bool>(n, false));

        int check = 0;
        queue<pair<int,int>> que;
        for(int i = 0; i < n; ++i){
            for(int j = 0; j < n; ++j){
                if(grid[i][j] == 1){
                    que.push({i,j});
                    vis[i][j] = true;
                    ++check;
                }
            }
        }
        if(check == n*n || check == 0) return -1;

        int ret = -1;
        while(que.size()){
            int sz = que.size();
            while(sz--){
                auto [a,b] = que.front(); que.pop();
                for(int i = 0; i < 4; ++i){
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < n && y >= 0 && y < n && vis[x][y] == false)
                    {
                        que.push({x,y});
                        vis[x][y] = true;
                    }
                }
            }
            ++ret;
        }
        return ret;
    }
};
